﻿/* 
 * Copyright 2010 Justin Pealing
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *     http://www.apache.org/licenses/LICENSE-2.0
 *     
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. 
 */

using System;
using System.IO;
using System.Collections.Generic;
using System.Text;
using Minnow.Web.Http;
using System.Reflection;

namespace Minnow.Web
{
    /// <summary>
    /// Enumeration of Http error codes
    /// </summary>
    public enum HttpErrorStatus
    {
        Status404,
        Status500
    }

    public class ErrorHandler : Dictionary<HttpErrorStatus, string>
    {
        public ErrorHandler()
        {
            this[HttpErrorStatus.Status404] = ResourceUtil.GetResource("Minnow.Web.HtmlContent.404.html");
            this[HttpErrorStatus.Status500] = ResourceUtil.GetResource("Minnow.Web.HtmlContent.500.html");
        }

        public Stream GetResponseStream(HttpErrorStatus Status)
        {
            byte[] bytes = Encoding.ASCII.GetBytes(this[Status]);
            return new MemoryStream(bytes);
        }

        public int GetHttpStatusCode(HttpErrorStatus Status)
        {
            switch(Status)
            {
                case HttpErrorStatus.Status404:
                    return 404;
                case HttpErrorStatus.Status500:
                    return 500;
            }

            throw new NotSupportedException("Unrecognised Status");
        }

        public void HandleError(ListenerHttpResponse response, HttpErrorStatus Status)
        {
            response.StatusCode = GetHttpStatusCode(Status);
            response.StatusDescription = GetHttpStatusDescription(Status);
            StreamUtils.CopyStream(this.GetResponseStream(Status), response.OutputStream);
        }


        public string GetHttpStatusDescription(HttpErrorStatus Status)
        {
            switch (Status)
            {
                case HttpErrorStatus.Status404:
                    return "Not Found";
                case HttpErrorStatus.Status500:
                    return "Internal Server Error";
            }

            throw new NotSupportedException("Unrecognised Status");
        }
    }
}
